package org.kjtc.controller;

import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.kjtc.service.WeChartService;
import org.kjtc.weChatUtil.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    private static Logger logger = Logger.getLogger(LoginController.class);

    @Autowired
    private WeChartService weChartService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @RequestMapping("")
    public String loginPage(){
        return "login";
    }

    /**
     * 微信登录
     * @param request
     * @param response
     * @param width
     * @param height
     */
    @RequestMapping("/loginQrCode")
    public void getQRCode(HttpServletRequest request, HttpServletResponse response, Integer width, Integer height){
        try {
            String url = CommonUtil.wechat_QrCode_url + "&uuid=";;
            String uuid = CommonUtil.getSNCode() + "_" + UUID.randomUUID().toString().replaceAll("-", "");
            request.getSession().setAttribute(uuid, request.getSession().getId());
            url += uuid;
            BufferedImage image = CommonUtil.createWeChatQRCode(url, width, height, ErrorCorrectionLevel.L);
            response.reset();
            Cookie cookie = new Cookie("uuid", uuid);
            response.addCookie(cookie);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            ImageIO.write(image, "png", outputStream);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
            outputStream = null;
            url = null;
            uuid = null;
            cookie = null;
        } catch (Exception e) {
            logger.error("生成二维码异常：" + e.getMessage());
        }
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/loginStatus")
    @ResponseBody
    public Object toLogin(HttpServletRequest request){

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", "0");
        Cookie[] cookies = request.getCookies();
        if (null != cookies && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("uuid".equals(cookie.getName())) {
                    String uuid = cookie.getValue();
                    String checkResult = CommonUtil.checkUUID(uuid);
                    if ("Success".equals(checkResult)) {
                        if (request.getSession() != null && request.getSession().getAttribute(uuid) != null &&
                                request.getSession().getId().equals(request.getSession().getAttribute(uuid))) {
                            if (redisTemplate.hasKey(uuid)) {
                                JSONObject json = JSONObject.fromObject(redisTemplate.opsForValue().get(uuid));
                                if (json.has("status") && json.has("openid")) {
                                    if ("1".equals(json.getString("status"))) {
                                        // 扫码成功
                                        map.put("status", "1");
                                        request.getSession().setAttribute(CommonUtil.SESSION_USER, json.getString("openid"));
                                    } else if ("2".equals(json.getString("status"))) {
                                        // 确认登录
                                        map.put("status", "2");
                                        map.put("url", "home");
                                        redisTemplate.delete(uuid);
                                    } else {
                                        map.put("status", "-1");
                                    }
                                } else {
                                    map.put("status", "-1");
                                }
                            }
                        }
                    } else if ("Timeout".equals(checkResult)) {
                        // 二维码过期
                        map.put("status", "3");
                    } else {
                        // 二维码异常
                        map.put("status", "-1");
                    }
                }
            }
        }
        return map;
    }
    @RequestMapping("/confirmLogin")
    @ResponseBody
    public Object confirmLogin(HttpServletRequest request, String uuid){

        Map<String, Object> map = new HashMap<String, Object>();
        if (redisTemplate.hasKey(uuid)) {
            JSONObject jsonObject = JSONObject.fromObject(redisTemplate.opsForValue().get(uuid));
            if (jsonObject.has("status")) {
                if ("1".equals(jsonObject.getString("status"))) {
                    if (jsonObject.has("openid") && redisTemplate.hasKey(jsonObject.getString("openid"))) {
                        jsonObject.put("openid", request.getSession().getAttribute(CommonUtil.SESSION_USER));
                        jsonObject.put("status", "2");
                        redisTemplate.opsForValue().set(uuid, jsonObject.toString(), System.currentTimeMillis() - Long.parseLong(uuid.split("_")[0]), TimeUnit.MILLISECONDS);
                        map.put("result", "Success");
                        map.put("url", "weChatApp/loginConfirm");
                    } else {
                        map.put("result", "Error");
                    }
                } else if ("2".equals(jsonObject.getString("status"))) {
                    map.put("result", "Invalid");
                } else {
                    map.put("result", "Invalid");
                }
            } else {
                map.put("result", "Invalid");
            }
        } else {
            map.put("result", "Timeout");
        }

        return map;
    }

    @RequestMapping("/home")
    public String home(HttpServletRequest request){
        if (request.getSession().getAttribute(CommonUtil.SESSION_USER) != null) {
            return "admin/main";
        }
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if ("uuid".equals(cookie.getName())) {
                }
            }
        }
        if (!CommonUtil.test_model) {
            return "login";
        } else {
            return "admin/main";
        }

    }

    @RequestMapping("/checkToken")
    @ResponseBody
    public String checkToken(HttpServletRequest request, HttpServletResponse response) throws Exception{
        logger.info("微信服务token验证");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");

        String method = request.getMethod();
        if ("GET".equals(method)) {
            if (signature != null && !signature.isEmpty() && CommonUtil.checkSignature(signature, timestamp, nonce)) {
                logger.info("微信服务token验证成功");
                // 随机字符串
                return request.getParameter("echostr");
            } else {
                logger.info("微信服务token验证失败");
                return null;
            }
        } else if ("POST".equals(method)) {
            if (CommonUtil.checkSignature(signature, timestamp, nonce)) {

            } else {
                logger.info("微信服务token验证失败");
                return null;
            }
        }
        return "";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session != null) {
            if (request.getSession().getAttribute(CommonUtil.SESSION_USER) != null) {
                redisTemplate.delete((String)request.getSession().getAttribute(CommonUtil.SESSION_USER));
            }
            session.invalidate();
        }
        return "login";
    }
}